package handler

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"micros/api/params"
	"micros/golbal"
	"micros/inits"
	"micros/model"
	"micros/pkg"
	"net/http"
	"strconv"
	"time"
)

func Register(c *gin.Context) {
	res := params.UserReq{}
	if err := c.ShouldBind(&res); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	var user model.User

	golbal.DB.Debug().Where("mobile=?", user.Mobile).Find(&user)

	if user.Mobile != "" {
		fmt.Println("手机号已存在")
	}

	m := model.User{

		Mobile:   res.Mobile,
		Password: pkg.Md5(res.Password),
	}

	golbal.DB.Debug().Create(&m)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "注册成功",
	})
}

func Login(c *gin.Context) {
	req := params.UserReq{}
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	var user model.User

	golbal.DB.Debug().Where("mobile=?", user.Mobile).Find(&user)

	handler, _ := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": handler,
	})
}

func Show(c *gin.Context) {
	show := params.Show{}
	if err := c.ShouldBind(&show); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	var user model.User
	golbal.DB.Debug().Where("id=?", user.ID).Find(&user)
	key := fmt.Sprintf("user")
	result, _ := golbal.Rdb.Get(inits.Ctx, key).Result()
	if result == "" {
		marshal, _ := json.Marshal(&user)
		golbal.Rdb.Set(inits.Ctx, key, marshal, time.Minute*10)
	} else {
		json.Unmarshal([]byte(result), &user)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "信息查询成功",
	})
}
